<template>
  <!-- 排班计划表单弹窗 -->
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      width="1460"
      draggable
      @close="closeDialog"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :inline="true"
        :rules="rules"
        label-width="80"
      >
        <h4 class="mb-[20px] mt-[0px]">发货单头信息</h4>
        <div class="search-container">
          <el-row>
            <el-col :span="8">
              <el-form-item label="工厂" prop="plantId">
                <el-select
                  v-if="!props.isReadonly"
                  v-model="formData.plantId"
                  placeholder="请输入工厂"
                  clearable
                  @change="changePlant"
                  style="width: 230px"
                >
                  <el-option
                    v-for="item in plantList"
                    :key="item.id"
                    :label="item.organizationCode"
                    :value="item.id"
                  />
                </el-select>
                <span v-else>{{ formData.plantCode }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8" v-if="props.isReadonly">
              <el-form-item label="发货单号">
                <span>{{ formData.exteriorDeliveryCode }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="供应商" prop="supplierId">
                <el-select
                  v-if="!props.isReadonly"
                  v-model="formData.supplierId"
                  value-key="id"
                  :disabled="formData.plantId === ''"
                  placeholder="请选择供应商"
                  clearable
                  @change="changePartner"
                >
                  <el-option
                    v-for="item in partnerList"
                    :key="item.id"
                    :label="item.partnerName"
                    :value="item.id"
                  />
                </el-select>
                <span v-else
                  >{{ formData.supplierCode }} -
                  {{ formData.supplierName }}</span
                >
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="交货地" prop="destinationDescription">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.destinationDescription"
                  placeholder="请输入交货地"
                  :disabled="formData.supplierId === ''"
                  clearable
                  type="textarea"
                  autosize
                  maxlength="255"
                  style="width: 568px"
                />
                <span v-else>{{ formData.destinationDescription }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="承运商" prop="generalCarrierId">
                <el-select
                  v-if="!props.isReadonly"
                  v-model="formData.generalCarrierId"
                  value-key="id"
                  :disabled="formData.plantId === ''"
                  placeholder="请选择承运商"
                  clearable
                  @change="changeGeneralCarrier"
                >
                  <el-option
                    v-for="item in generalCarrierList"
                    :key="item.id"
                    :label="`${item.generalCarrierCode}-${item.generalCarrierName}`"
                    :value="item.id"
                  />
                </el-select>
                <span v-else
                  >{{ formData.generalCarrierCode }} -
                  {{ formData.generalCarrierName }}</span
                >
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="车牌号" prop="vehicleCode">
                <el-select
                  v-if="!props.isReadonly"
                  :disabled="formData.generalCarrierId === ''"
                  v-model="formData.vehicleCode"
                  value-key="id"
                  placeholder="请选择车牌号"
                  @change="changeVehicle"
                  clearable
                >
                  <el-option
                    v-for="item in carrierVehicleList"
                    :key="item.id"
                    :label="item.vehicleCode"
                    :value="item.id"
                  />
                </el-select>
                <span v-else>{{ formData.vehicleCode }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="车型" prop="vehicleTypeName">
                <el-input
                  v-if="!props.isReadonly"
                  :disabled="formData.vehicleCode === ''"
                  v-model="formData.vehicleTypeName"
                  placeholder="请输入车型"
                  clearable
                  maxlength="25"
                />
                <span v-else>{{ formData.vehicleTypeName }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="司机" prop="driverName">
                <el-select
                  v-if="!props.isReadonly"
                  :disabled="formData.generalCarrierId === ''"
                  v-model="formData.driverName"
                  value-key="id"
                  placeholder="请选择司机"
                  @change="changeDriver"
                  clearable
                >
                  <el-option
                    v-for="item in carrierDriverList"
                    :key="item.id"
                    :label="item.driverName"
                    :value="item.id"
                  />
                </el-select>
                <span v-else>{{ formData.driverName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="联系电话" prop="driverPhone">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.driverPhone"
                  :disabled="formData.driverName === ''"
                  placeholder="请输入交货地"
                  clearable
                  maxlength="25"
                />
                <span v-else>{{ formData.driverPhone }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="16">
              <el-form-item label="备注" prop="remarks">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.remarks"
                  placeholder="请输入备注"
                  clearable
                  type="textarea"
                  autosize
                  maxlength="255"
                  style="width: 946px"
                />
                <span v-else>{{ formData.remarks }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <h4 class="mb-[20px] mt-[20px]">发货单明细</h4>
        <el-tabs v-model="defaultTabValue" type="border-card">
          <el-tab-pane label="明细" :name="1">
            <el-card shadow="never" class="table-container">
              <template #header>
                <el-button
                  type="success"
                  plain
                  @click="openDialogAdd"
                  v-if="!props.isReadonly"
                >
                  <i-ep-plus />
                  库存选择</el-button
                >
                <!-- <el-button
                  type="danger"
                  plain
                  @click="handleDel"
                  v-if="!props.isReadonly"
                >
                  清空</el-button
                > -->
              </template>

              <div class="formTable">
                <el-table
                  :data="formData.mesProduceTransferFormDTOS"
                  style="width: 100%"
                  :key="Math.random"
                  border
                >
                  <el-table-column
                    type="index"
                    label="序号"
                    align="center"
                    width="100"
                  />
                  <el-table-column
                    label="工厂"
                    props="plantCode"
                    min-width="150"
                  >
                    <template #default="{ row }">
                      <span>{{ row.plantCode }}</span>
                    </template>
                  </el-table-column>

                  <el-table-column
                    label="工作中心"
                    props="workCenterCode"
                    min-width="120"
                  >
                    <template #default="{ row }">
                      <span
                        >{{ row.workCenterCode }}-{{ row.workCenterName }}</span
                      >
                    </template>
                  </el-table-column>

                  <el-table-column
                    label="物料条码"
                    props="produceTransferFormCode"
                    min-width="150"
                  >
                    <template #default="{ row }">
                      <span>{{ row.produceTransferFormCode }}</span>
                    </template>
                  </el-table-column>

                  <el-table-column
                    label="存货编码"
                    props="materialCode"
                    min-width="150"
                  >
                    <template #default="{ row }">
                      <span>{{ row.materialCode }}-{{ row.materialName }}</span>
                    </template>
                  </el-table-column>

                  <el-table-column label="批次" props="remarks" min-width="150">
                    <template #default="{ row }">
                      <span>{{ row.remarks }}</span>
                    </template>
                  </el-table-column>

                  <el-table-column
                    label="数量"
                    props="productQuantity"
                    min-width="150"
                  >
                    <template #default="{ row }">
                      <span>{{ row.productQuantity }}</span>
                    </template>
                  </el-table-column>

                  <el-table-column
                    label="数量单位"
                    props="quantityUnit"
                    min-width="150"
                    align="center"
                  >
                    <template #default="scope">
                      {{
                        useDictionary("MeasurementUnit", scope.row.quantityUnit)
                      }}
                    </template>
                  </el-table-column>

                  <el-table-column
                    fixed="right"
                    align="center"
                    label="操作"
                    width="100"
                    v-if="!props.isReadonly"
                  >
                    <template #default="scope">
                      <el-button
                        type="danger"
                        link
                        @click.stop="handleDelete(scope.$index)"
                        ><i-ep-delete />
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                  <el-table-column
                    fixed="right"
                    align="center"
                    label="操作"
                    width="120"
                    v-if="props.isReadonly"
                  >
                    <template #default="scope">
                      <el-button
                        type="primary"
                        link
                        @click="print(scope.$index)"
                      >
                        <el-icon :size="20"><Printer /></el-icon>
                        打印包装
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-card>
          </el-tab-pane>
          <el-tab-pane label="合计" :name="2">
            <el-card shadow="never" class="table-container">
              <div class="formTable">
                <el-table
                  :data="formData.mesProduceTransferFormDTOSSum"
                  style="width: 100%"
                  :key="Math.random"
                  border
                >
                  <el-table-column
                    type="index"
                    label="序号"
                    align="center"
                    width="100"
                  />
                  <el-table-column
                    label="工厂"
                    props="plantCode"
                    min-width="120"
                  >
                    <template #default="{ row }">
                      <span>{{ row.plantCode }}</span>
                    </template>
                  </el-table-column>

                  <el-table-column
                    label="工作中心"
                    props="workCenterCode"
                    min-width="150"
                  >
                    <template #default="{ row }">
                      <span>{{ row.workCenterCode }}</span>
                    </template>
                  </el-table-column>

                  <el-table-column
                    label="存货编码"
                    props="materialCode"
                    min-width="150"
                  >
                    <template #default="{ row }">
                      <span>{{ row.materialCode }}</span>
                    </template>
                  </el-table-column>

                  <el-table-column label="批次" props="remarks" min-width="150">
                    <template #default="{ row }">
                      <span>{{ row.remarks }}</span>
                    </template>
                  </el-table-column>

                  <el-table-column
                    label="数量"
                    props="productQuantity"
                    min-width="150"
                  >
                    <template #default="{ row }">
                      <span>{{ row.productQuantity }}</span>
                    </template>
                  </el-table-column>

                  <el-table-column label="箱数" props="count">
                    <template #default="{ row }">
                      <span>{{ row.count }}</span>
                    </template>
                  </el-table-column>

                  <el-table-column
                    label="数量单位"
                    props="quantityUnit"
                    min-width="150"
                    align="center"
                  >
                    <template #default="scope">
                      {{
                        useDictionary("MeasurementUnit", scope.row.quantityUnit)
                      }}
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-card>
          </el-tab-pane>
        </el-tabs>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <mesExteriorDelivery-add
      v-model:visible="addDialog123.visible"
      :title="addDialog123.title"
      :isMultiple="true"
      :data="addDialog123.data"
      :is-readonly="addDialog123.readvisible"
      @echo-info="getSelect"
      @change-visible="changeVisible"
    />
    <div id="printBox" v-if="isPrint" style="opacity: 0">
      <div
        style="margin-bottom: 20px"
        v-for="item in printData"
        :key="item?.id"
      >
        <div
          :id="`printId_${item?.id || ''}`"
          style="width: 394px; height: 394px"
        >
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          <!-- <canvas :id="`barcode_${item?.id || ''}`"></canvas> -->
          <div
            style="
              font-size: 12px;
              font-weight: 600;
              word-break: break-all;
              width: 390px;
            "
          >
            <span style="font-size: 18px; font-weight: 100; margin-right: 20px"
              ><text
                style="font-size: 20px; font-weight: 600; margin-right: 20px"
                >{{ item?.externalCode || "" }}</text
              ></span
            >
          </div>

          <div style="font-size: 14px; margin-bottom: -10px; width: 390px">
            <span
              style="
                font-size: 18px;
                font-weight: 100;
                margin-right: 20px;
                font-weight: 600;
              "
              >存货编码：&nbsp;<text
                style="font-size: 20px; font-weight: 600; margin-right: 20px"
                >{{ item?.materialCode || "" }}</text
              ></span
            >
            <span
              style="
                font-size: 18px;
                font-weight: 100;
                margin-right: 20px;
                font-weight: 600;
              "
              >材质：&nbsp;<text style="font-size: 20px; font-weight: 600">{{
                item?.materialQuality || ""
              }}</text></span
            >
          </div>
          <div style="font-size: 14px; margin-bottom: -10px; width: 390px">
            <br />
            <span
              style="
                font-size: 18px;
                font-weight: 100;
                margin-right: 20px;
                font-weight: 600;
              "
              >规格型号：&nbsp;<text
                style="font-size: 20px; font-weight: 600"
                >{{ item?.materialSpecification || "" }}</text
              ></span
            >
          </div>
          <div style="font-size: 14px; margin-bottom: -10px; width: 390px">
            <br />
            <span style="font-size: 18px; margin-right: 20px; font-weight: 600"
              >图号：&nbsp;<text style="font-size: 20px; font-weight: 600">{{
                item?.figureNumber || ""
              }}</text></span
            >
          </div>
          <div style="font-size: 14px; margin-bottom: 0px; width: 390px">
            <br /><span
              style="
                font-size: 18px;
                font-weight: 100;
                margin-right: 10px;
                font-weight: 600;
              "
              >生产批次：<text
                style="font-size: 20px; font-weight: 600; margin-right: 10px"
                >{{ item?.remarks || "" }}</text
              ></span
            >
            <span
              style="
                font-size: 18px;
                font-weight: 100;
                margin-right: 20px;
                font-weight: 600;
              "
              >数量：&nbsp;<text style="font-size: 20px; font-weight: 600"
                >{{ item?.productQuantity || "" }}
                {{ item?.unitName || "" }}</text
              >
            </span>
          </div>
          <div style="height: 5px"></div>
          <div style="font-size: 12px; width: 390px; margin-bottom: 1px">
            <span
              style="
                font-size: 12px;
                font-weight: 100;
                margin-right: 20px;
                font-weight: 600;
              "
              >打印时间：&nbsp;<text>{{ item?.createTime || "" }}</text></span
            >
            <span
              style="
                font-size: 12px;
                font-weight: 100;
                margin-right: 20px;
                font-weight: 600;
              "
              >打印人：&nbsp;<text
                >{{ item?.createdUserName || "" }}&nbsp;</text
              ></span
            >
          </div>
          <div style="height: 5px"></div>
          <div style="font-size: 14px; width: 400px; display: flex">
            <span
              style="
                flex: 1;
                font-weight: 100;
                font-size: 14px;
                margin-right: 20px;
                font-weight: 600;
              "
              >操作者1：&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span
            >
            <span
              style="
                flex: 1;
                font-weight: 100;
                font-size: 14px;
                margin-right: 20px;
                font-weight: 600;
              "
              >操作者2：&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span
            >
            <span
              style="
                flex: 1;
                font-weight: 100;
                font-size: 14px;
                margin-right: 20px;
                font-weight: 600;
              "
              >检&nbsp;查：&nbsp;&nbsp;&nbsp;&nbsp;</span
            >
          </div>
          <div
            style="
              font-size: 17px;
              margin-bottom: 0px;
              width: 300px;
              font-weight: 600;
            "
          ></div>
        </div>
        <div style="margin-top: 500px; text-align: center">
          <div style="display: flex; justify-content: center; gap: 10px">
            <!--          <el-button size="small" @click="getPrintData()">打印</el-button>
          <el-button size="small" @click="close()">返回</el-button>-->
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import {
  getDriverList,
  getVehicleList,
  getGeneralCarrierList,
  getSupplierList,
} from "@/utils/commonData";
import { useDictionary } from "@/utils/useTable";
import { getLodop } from "@/utils/LocalLodopFuncs";
import { RootObject } from "@/views/demo/iframePrintUnitOne/index";

defineOptions({
  name: "MesExteriorDeliveryEdit",
  inheritAttrs: false,
});
let defaultTabValue = ref(1);
const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});
// 接收 人员选择器回调参数
function getSelect(options: any) {
  console.log(options);
  for (const value of options) {
    console.log(value); // 输出: 1, 2, 3
    formData.mesProduceTransferFormDTOS.push(value);
  }
  formData.mesProduceTransferFormDTOS = uniqueByProperty(
    formData.mesProduceTransferFormDTOS,
    "id"
  );
  console.log(formData.mesProduceTransferFormDTOS);
}

function uniqueByProperty<T, K extends keyof T>(arr: T[], key: K): T[] {
  return arr.filter((item, index, self) => {
    return self.findIndex((t) => t[key] === item[key]) === index;
  });
}
7;
const addDialog123 = reactive<DialogOption>({
  visible: false,
  title: "",
  data: [],
});
function changeVisible(value: boolean) {
  addDialog123.visible = value;
  if (!value) {
    addDialog123.data = {};
  }
}

/** 打开外协发货单表单弹窗 */
function openDialogAdd() {
  addDialog123.title = "库存选择";
  addDialog123.visible = true;
}

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData = reactive({
  id: "",
  exteriorDeliveryCode: "",
  organizationId: "",
  organizationCode: "",
  plantId: "",
  plantCode: "",
  deliveryState: "",
  supplierId: "",
  supplierCode: "",
  supplierName: "",
  generalCarrierId: "",
  generalCarrierCode: "",
  generalCarrierName: "",
  vehicleCode: "",
  vehicleTypeId: "",
  vehicleTypeCode: "",
  vehicleTypeName: "",
  vehicleRegistration: "",
  driverName: "",
  driverPhone: "",
  driverRegistration: "",
  destinationDescription: "",
  sendingTime: "",
  sendingUserId: "",
  sendingUserName: "",
  arriveTime: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: 1,
  deleted: "",
  mesProduceTransferFormDTOS: [
    // {
    //   id: "",
    //   produceTransferFormCode: "",
    //   workingFormId: "",
    //   workingFormCode: "",
    //   externalCode: "",
    //   organizationId: "",
    //   organizationCode: "",
    //   plantId: "",
    //   plantCode: "",
    //   producePlanId: "",
    //   producePlanCode: "",
    //   produceOrderId: "",
    //   produceOrderCode: "",
    //   routingId: "",
    //   materialId: "",
    //   materialCode: "",
    //   workCenterId: "",
    //   workCenterCode: "",
    //   processId: "",
    //   productQuantity: "",
    //   quantityUnit: "",
    //   isValid: "",
    //   produceState: "",
    //   version: "",
    //   remarks: "",
    //   createTime: "",
    //   createdUserId: "",
    //   createdUserName: "",
    //   lastUpdateTime: "",
    //   lastUpdatedUserId: "",
    //   lastUpdatedUserName: "",
    //   enabled: "",
    //   deleted: "",
    // },
  ],
  mesProduceTransferFormDTOSSum: [
    {
      plantId: "",
      plantCode: "",
      materialId: "",
      materialCode: "",
      workCenterId: "",
      workCenterCode: "",
      productQuantity: "",
      quantityUnit: "",
      remarks: "",
    },
  ],
});

/** rules规则 */
const rules = reactive({
  plantId: [{ required: true, message: "请选择工厂", trigger: "blur" }],
  supplierId: [{ required: true, message: "请选择客户", trigger: "blur" }],
  destinationDescription: [
    { required: true, message: "请输入交货地", trigger: "blur" },
  ],
  generalCarrierId: [{ message: "请选择承运商", trigger: "blur" }],
  vehicleCode: [{ message: "请选择车牌号", trigger: "blur" }],
  vehicleTypeName: [{ message: "请输入车型", trigger: "blur" }],
  driverName: [{ message: "请选择司机", trigger: "blur" }],
  driverPhone: [{ message: "请选择联系电话", trigger: "blur" }],
});

/** 删除行 */
const handleDelete = (index: any) => {
  if (formData.mesProduceTransferFormDTOS.length == 1) {
    ElMessage.error("删除失败，最少有一条数据。");
  } else {
    formData.mesProduceTransferFormDTOS.splice(index, 1);
  }
};

const mesProduceTransferFormDTOS = {
  id: "",
  produceTransferFormCode: "",
  workingFormId: "",
  workingFormCode: "",
  externalCode: "",
  organizationId: "",
  organizationCode: "",
  plantId: "",
  plantCode: "",
  producePlanId: "",
  producePlanCode: "",
  produceOrderId: "",
  produceOrderCode: "",
  routingId: "",
  materialId: "",
  materialCode: "",
  workCenterId: "",
  workCenterCode: "",
  processId: "",
  productQuantity: "",
  quantityUnit: "",
  isValid: "",
  produceState: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
  count: 0,
};

/** 清空 */
const handleDel = () => {
  formData.mesProduceTransferFormDTOS = [];
  formData.mesProduceTransferFormDTOSSum = [];
};

/** 编辑时赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, props.data);
    }
    //获取供应商名称
    partnerList.value.forEach((item) => {
      if (item.id === props.data.supplierId) {
        formData.supplierName = item.partnerName;
      }
    });
    //获取承运商名称
    generalCarrierList.value.forEach((item) => {
      if (item.id === props.data.generalCarrierId) {
        formData.generalCarrierName = item.generalCarrierName;
      }
    });
  }
);
watch(
  () => formData.mesProduceTransferFormDTOS,
  (newVal: any) => {
    console.log(newVal);

    // 使用 reduce 方法来分组并计算合计
    const groupedItems = newVal.reduce((acc: any, item: any) => {
      const key = `${item.plantCode}-${item.materialCode}-${item.workCenterCode}-${item.remarks}-${item.quantityUnit}`; // 根据 category 和 subcategory 生成唯一的键
      if (!acc[key]) {
        // 如果这个分组还不存在，则创建一个新的分组，并初始化 quantity 为当前项的值
        acc[key] = {
          items: [item], // 可以保存原始项（如果需要的话）
          plantId: item.plantId,
          plantCode: item.plantCode,
          materialId: item.materialId,
          materialCode: item.materialCode,
          workCenterId: item.workCenterId,
          workCenterCode: item.workCenterCode,
          productQuantity: item.productQuantity,
          quantityUnit: item.quantityUnit,
          remarks: item.remarks,
          count: 1,
        };
      } else {
        // 如果这个分组已经存在，则累加 quantity 并把当前项添加到 items 数组中
        acc[key].productQuantity += item.productQuantity;
        acc[key].count = acc[key].count + 1;
        acc[key].items.push(item);
      }
      return acc;
    }, {});

    // 将结果转换为数组（如果需要的话）
    formData.mesProduceTransferFormDTOSSum = Object.values(groupedItems);

    // 输出结果
    console.log(formData.mesProduceTransferFormDTOSSum);
  }
);
/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
  }
);
/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
  handleDel();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.mesProduceTransferFormDTOS = [mesProduceTransferFormDTOS];
  formData.id = "";
  formData.exteriorDeliveryCode = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.deliveryState = "";
  formData.supplierId = "";
  formData.supplierCode = "";
  formData.supplierName = "";
  formData.generalCarrierId = "";
  formData.generalCarrierCode = "";
  formData.generalCarrierName = "";
  formData.vehicleCode = "";
  formData.vehicleTypeId = "";
  formData.vehicleTypeCode = "";
  formData.vehicleTypeName = "";
  formData.vehicleRegistration = "";
  formData.driverName = "";
  formData.driverPhone = "";
  formData.driverRegistration = "";
  formData.destinationDescription = "";
  formData.sendingTime = "";
  formData.sendingUserId = "";
  formData.sendingUserName = "";
  formData.arriveTime = "";
  formData.version = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.deleted = "";
}

const loading = ref(false);

function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      if (formData.mesProduceTransferFormDTOS.length == 0) {
        ElMessage.error("未选择发货明细信息，无法创建/修改发货单！");
        return;
      }
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      console.log("formData", toRaw(formData));
      await request({
        url: "/mes/mesexteriordelivery/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// async function getdetails() {
//   let sondetails = await request({
//     url: "/mes/messhiftschedule/getDetails",
//     method: "post",
//     data: formData,
//   }).finally(() => {
//     loading.value = false;
//   });
//   formData.details = sondetails.data;
// }
onMounted(() => {
  getPlantList();
  getSupplier();
  getGeneralCarrier();
});
//供应商、承运商数据 code-name
async function getSupplier() {
  partnerList.value = (await getSupplierList()) || [];
}
async function getGeneralCarrier() {
  generalCarrierList.value = (await getGeneralCarrierList()) || [];
}

const IFRAME_URL = import.meta.env.VITE_APP_IFRAME_URL;
const print = (row) => {
  const url = formData.mesProduceTransferFormDTOS[row].id;
  console.log(url);
  ElMessageBox.confirm(`请确认是否打印？`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    beforeClose: (action, instance, done) => {
      if (action === "confirm") {
        // 开启按钮加载
        instance.confirmButtonLoading = true;
        // 调用打印页面
        // 跳转到指定页面
        insertOperateLog(url);
        // window.location.href = `${IFRAME_URL}iframePrintUnitOne?id=${url}`;
        isPrint.value = true;
        printId.value = url;
        getPrintData();
        done();
      } else {
        done();
      }
    },
  }).catch(() => {});
};
//打印日志信息
const operateLog = ref({
  logLevel: "INFO",
  applicationName: "jcfk-mes",
  modular: "外协发货开始",
  businessType: "打印",
  info: "",
});
//开始打印
async function insertOperateLog(id: any) {
  operateLog.value.info = id;
  await request({
    method: "POST",
    url: "/system/sysOperateLog/insert",
    data: operateLog.value,
  });
}

//工厂列表
const plantList: Ref<any> = ref([]);
const getPlantList = async () => {
  const { data } = await request({
    url: "system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plantList.value = data;
};

const partnerList: any = ref(); // 委外供应商/客户
const generalCarrierList: any = ref(); // 承运商
const carrierVehicleList: any = ref(); // 车辆
const carrierDriverList: any = ref(); // 司机
const changePlant = async (id: any) => {
  const data = plantList.value.find((item: any) => item.id === id);
  formData.plantId = data.id;
  formData.plantCode = data.organizationCode;
  //工厂变更清除关联内容
  formData.supplierId = "";
  formData.supplierCode = "";
  formData.supplierName = "";
  formData.generalCarrierId = "";
  formData.generalCarrierCode = "";
  formData.generalCarrierName = "";
  formData.vehicleCode = "";
  formData.vehicleTypeId = "";
  formData.vehicleTypeCode = "";
  formData.vehicleTypeName = "";
  formData.vehicleRegistration = "";
  formData.driverName = "";
  formData.driverPhone = "";
  formData.driverRegistration = "";
  partnerList.value = (await getSupplierList(id)) || [];
  generalCarrierList.value = (await getGeneralCarrierList()) || [];
};
const changePartner = async (id: any) => {
  formData.supplierId = id;
  const partnerData = partnerList.value.find((item: any) => item.id === id);
  formData.supplierCode = partnerData.partnerCode;
  formData.supplierName = partnerData.partnerName;
  formData.destinationDescription =
    partnerData.country +
    partnerData.province +
    partnerData.city +
    partnerData.region +
    partnerData.street +
    partnerData.houseCode +
    partnerData.zipCode;
};
const changeGeneralCarrier = async (id: any) => {
  formData.generalCarrierId = id;
  const genData = generalCarrierList.value.find((item: any) => item.id === id);
  formData.generalCarrierCode = genData.generalCarrierCode;
  formData.generalCarrierName = genData.generalCarrierName;
  formData.vehicleCode = "";
  formData.vehicleTypeId = "";
  formData.vehicleTypeCode = "";
  formData.vehicleTypeName = "";
  formData.vehicleRegistration = "";
  formData.driverName = "";
  formData.driverPhone = "";
  formData.driverRegistration = "";
  carrierVehicleList.value = (await getVehicleList(id)) || [];
  carrierDriverList.value = (await getDriverList(id)) || [];
};
const changeVehicle = async (id: any) => {
  const carData = carrierVehicleList.value.find((item: any) => item.id === id);
  formData.vehicleCode = carData.vehicleCode;
  formData.vehicleTypeId = carData.vehicleTypeId;
  formData.vehicleTypeCode = carData.vehicleTypeCode;
  formData.vehicleTypeName = carData.vehicleTypeName;
  formData.vehicleRegistration = carData.vehicleRegistration;
};
const changeDriver = async (id: any) => {
  const carData = carrierDriverList.value.find((item: any) => item.id === id);
  formData.driverName = carData.driverName;
  formData.driverPhone = carData.driverPhone;
  formData.driverRegistration = carData.driverRegistration;
};
// 打印数据，数组形式
const printData = ref<RootObject[]>([]);
const isPrint = ref(false);
let printId = ref("");
// 获取打印数据
async function getPrintData() {
  const { data } = await request({
    url: `/mes/mesproducetransferform/get/${printId.value}`,
    method: "get",
    data: {},
  }).finally(() => {});
  //printData.value = [data, data, data]; //多张打印
  printData.value = [data]; //单张打印

  nextTick(() => {
    printData.value?.map(async (e) => {
      const qrCodeId = `barcode_${e?.id || ""}`;
      const qrCodeElement = document.getElementById(qrCodeId);

      if (qrCodeElement) {
        try {
          await QRCode.toCanvas(qrCodeElement, e.externalCode || "", {
            width: 100, // 可以根据需要调整二维码的大小
            margin: 1, // 可以根据需要调整二维码的边距
          });
        } catch (err) {
          console.error("Error generating QR code:", err);
        }
      }
    });
  });
  setTimeout(() => {
    let LODOP = getLodop();
    LODOP.PRINT_INIT(`包装打印-${printId.value}`);
    // LODOP.SET_LICENSES(
    //   defaultSettings.printCompany,
    //   defaultSettings.printLicenses,
    //   "",
    //   ""
    // );
    printData.value?.map((e) => {
      printFun(e, LODOP);
    });
    //LODOP.SET_PRINTER_INDEX("ZDesigner ZT231-203dpi ZPL");
    //LODOP.PRINT(); // 打印
    console.log(LODOP.Printers.list);
    LODOP.PREVIEW(); // 预览
    isPrint.value = false;
    window.parent.postMessage("打印中，请稍后...", "*");
    insertOperateLog(printId.value);
  }, 1000);
}

function printFun(pitem: any, LODOP: any) {
  LODOP.SET_PRINT_PAGESIZE(1, "100mm", "100mm", ""); // 设置纸张类型（方向、宽度、高度、纸张类型名称）
  //LODOP.ADD_PRINT_RECT(0, 5, 310, 220, 0, 1); //边框设置：上、左、宽、高、线条：0实线 1虚线
  //LODOP.SET_PRINT_STYLE("FontSize", 7.5);
  //LODOP.SET_PRINT_STYLE("FontName", "cursive"); // 需要服务端机器安装同样字体，才能生效
  LODOP.ADD_PRINT_HTM(
    "40mm",
    "10mm",
    "100mm",
    "100mm",
    document.getElementById(`printId_${pitem?.id || ""}`)?.innerHTML
  );
  LODOP.ADD_PRINT_BARCODE(
    "5mm",
    "30mm",
    "40mm",
    "40mm",
    "QRCode",
    pitem?.externalCode || ""
  );
  LODOP.NEWPAGE(); //另起一页
}
</script>

<style lang="scss" scoped>
h4 {
  font-weight: 400;
  color: #000;
  padding-left: 10px;
  font-size: 14px;
  line-height: 14px;
}
.formTable {
  :deep(.el-form-item) {
    margin-right: 0 !important;
  }
}
:deep(.el-dialog .el-dialog__body) {
  overflow-y: auto;
  height: 65vh;
}
:deep(.search-container .el-input.el-input--default.el-input--suffix) {
  // 固定宽度
  width: 190px !important;
}
:deep(.search-container .el-form-item--default .el-form-item__label) {
  // 固定宽度
  justify-content: end;
}
</style>
